package com.atguigu.r2dbc.config.converter;

import com.atguigu.r2dbc.entity.Author;
import com.atguigu.r2dbc.entity.BookAuthor;
import io.r2dbc.spi.Row;
import io.r2dbc.spi.RowMetadata;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.convert.ReadingConverter;

import java.time.Instant;

/**
 * @author Jungle
 * @create 2024-01-17 10:59
 */
@ReadingConverter //读取数据库数据的时候
@Slf4j
public class BookAuthorConverter implements Converter<Row, BookAuthor> {
    // 1、@Query指定了sql如何发送
    // 2、自定义BookConverter指定了数据库返回的一Row数据，怎么封装成Book
    // 3)、配置R2dbccustomConversions 组件，让 BookConverter加入其中生效

    @Override
    public BookAuthor convert(Row source) {
        // 这里只能一个个get不能对象拷贝

        BookAuthor book = new BookAuthor();
        Long id = source.get("id", Long.class);
        book.setId(id);
        String title = source.get("title", String.class);
        book.setTitle(title);
        Long authorId = source.get("author_id", Long.class);
        book.setAuthorId(authorId);
        Instant publishTime = source.get("publish_time", Instant.class);
        book.setPublishTime(publishTime);


        RowMetadata metadata = source.getMetadata();
        //这里采用兼容，如果定义了自己的vo,不需要加判断
        if (metadata.contains("name")&&metadata.contains("id_number")) {
            String name = source.get("name", String.class);
            Long idNumber = source.get("id_number",Long.class);
            Author author = new Author();
            author.setId(Long.parseLong(String.valueOf(authorId)));
            author.setName(name);
            author.setIdNumber(Long.parseLong(String.valueOf(idNumber)));
            book.setAuthor(author);
        }
        return book;
    }
}
